package com.tgy.JUC.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/***
 * @ClassName: Demo1ajax
 * @Description: 异步调用
 * 异步调用  CompletableFuture
 * 成功回调
 * 失败回调
 * @Auther: 送你一块二向箔
 * @Date: 11:39 2022/3/15
 * @version : V1.0
 */
public class Demo1ajax {
    public static void main(String[] args) {
        run2();
    }
    public static void run1(){
        //无返回值的异步回调
        CompletableFuture<Void> completableFuture =CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"runAsync void");
        });

        System.out.println("1`11");

        try {
            completableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void run2(){
        //有返回值的异步回调
        CompletableFuture<String> completableFuture =CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 1/0;
            System.out.println(Thread.currentThread().getName()+"runAsync String");
            return "success";
        });

        System.out.println("延迟后执行");
        try {
            System.out.println(completableFuture.whenComplete((t, u) -> {
                System.out.println("t====》" + t);//t为正常结果的返回值
                System.out.println("u====》" + u);//u为错误结果的返回值
            }).exceptionally((e) -> {
                System.out.println(e.getMessage());
                return "500";
            }).get());
            String s = completableFuture.get();
            System.out.println("结果返回值"+s);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
